package com.example.hos_samples.dynamic.slice;

import com.example.hos_samples.ResourceTable;
import com.example.hos_samples.components.dynameic.DynScoped;
import com.example.hos_samples.components.dynameic.DynSingle;
import com.example.hos_samples.di.AppModule;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import org.koin.core.context.DefaultContextExt;
import org.koin.core.qualifier.Qualifier;
import org.koin.core.scope.Scope;
import org.koin.hos.ext.hos.ContextExt;

public class DynamicAbilitySlice extends AbilitySlice {

    private DynSingle single;
    private DynScoped scope;
    private Button dynButton;
    private Text dynLabel;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_dynamic);

        initInfo();
    }

    private void initInfo() {
        single = ContextExt.get(this, DynSingle.class);
        try {
            scope = ContextExt
                    .getKoin(this)
                    .createScope("id", Qualifier.named("dynamic_scope"))
                    .get(DynScoped.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        dynLabel = (Text) findComponentById(ResourceTable.Id_text_helloworld);
        dynButton = (Button) findComponentById(ResourceTable.Id_dyn_button);
        dynButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                DefaultContextExt.unloadKoinModules(AppModule.dynamicModule);
                DefaultContextExt.loadKoinModules(AppModule.dynamicModule);

                dynButton.setVisibility(Component.HIDE);

                assert !single.equals(ContextExt.get(DynamicAbilitySlice.this, DynSingle.class));
                try {
                    Scope scope1 = ContextExt.getKoin(DynamicAbilitySlice.this)
                            .getOrCreateScope("id", Qualifier.named("dynamic_scope"));
                    assert !scope.equals(scope1.get(DynScoped.class));

                    dynLabel.setText("reload ok!");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
